import react, { Component } from 'react'
import { Icon } from 'antd'
import styles from './index.less'


class Select extends Component {
  constructor(props) {
    super(props)
    this.state = {
      expand: false,
      selected: ''
    }
  }

  // 验证 data 格式
  vali = (data) => {
    if (Array.isArray(data)) {
      if (data.every(item => typeof item === 'object')) {
        if (data.every(item => item.value !== undefined && item.value !== null && item.label !== undefined && item.label !== null)) {
          return true
        } else {
          return 'data 每个元素的 value 和 label 属性不能是 undefined 和 null'
        }
      } else {
        return 'data 需要是对象数组'
      }
    } else {
      return 'data 需要是数组'
    }
  }

  // 渲染选项
  renderOptions = (valid) => {
    return (
      <ul
        className={`simple_options ${this.state.expand ? 'expanded' : ''}`}
      >
        {
          valid ? this.props.data.map((item, index) => {
            return (
              <li
                key={index}
                className={`simple_option`}
                onClick={(e) => {
                  typeof this.props.onChange === 'function' ? this.props.onChange(item.value, item) : null
                }}
              >
                {item.label}
              </li>
            )
          }) : null
        }
      </ul>
    )
  }

  render() {
    let { data, value } = this.props
    let res = this.vali(data)
    if (res !== true) {
      console.error(res)
      data = []
    }

    let tempLabel = value
    data.map(item => item.value === value ? tempLabel = item.label : tempLabel)

    return (
      <div
        className={`simple_select ${this.props.className}`}
      >
        <div
          className={`simple_selection`}
          tabIndex='0'
          onClick={(e) => {
            this.setState({
              expand: !this.state.expand
            })
          }}
          onBlur={(e) => {
            setTimeout(() => {
              this.setState({
                expand: false
              })
            }, 110)
          }}
        >
          <span className={`simple_selection_text`}>{tempLabel}</span>
          <Icon
            type={this.state.expand ? 'up' : 'down'}
          ></Icon>
        </div>
        {
          this.renderOptions(res === true ? true : false)
        }
      </div>
    )
  }
}

export default Select